//
//  NSString+AttrstrPrice.m
//  ShunLianPower2
//
//  Created by 顺联网络 on 2017/11/15.
//  Copyright © 2017年 陈镇. All rights reserved.
//

#import "NSString+SLAdd.h"
@implementation NSString (SLAdd)

- (NSMutableAttributedString *)sl_generateRMBSimpleAttributedStringWithFont:(UIFont*)font {
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"¥%@",self]];
    [attrStr addAttribute:NSFontAttributeName
                    value:font
                    range:NSMakeRange(0, 1)];
    return attrStr;
}

- (NSMutableAttributedString *)sl_generateRMBSimpleAttributedStringWithFont10 {
    return [self sl_generateRMBSimpleAttributedStringWithFont:[UIFont systemFontOfSize:10.0f]];
}

 - (NSMutableAttributedString *)sl_generateRMBSimpleDeleteLineAttributedStringWithFont {
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"¥%@",self]];
    [attrStr addAttribute:NSBaselineOffsetAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, attrStr.length)];
    [attrStr addAttribute:NSStrikethroughStyleAttributeName
                    value:[NSNumber numberWithInteger:NSUnderlineStyleSingle]
                    range:NSMakeRange(0, attrStr.length)];
     
    //font color is 0x858585
    [attrStr addAttribute:NSStrikethroughColorAttributeName value:[UIColor colorWithRed:133.f/255.f green:133.f/255.f blue:133.f/255.f alpha:1] range:NSMakeRange(0, attrStr.length)];
    return attrStr;
}

 - (CGSize)sl_imageSizeByComponentsSeparated {
    /* imageURL 格式
     "http://e.hiphotos.baidu.com/zhidao/pic/item/ac345982b2b7d0a2284d772bcdef76094a369afb.jpg?w=1920&h=1200"
     */
    if (![self hasPrefix:@"http"]) {
        return CGSizeMake(0, 0);
    }
    NSDictionary *dic = [self sl_parameterByComponentsSeparated];
    NSString *w = dic[@"w"];
    NSString *h = dic[@"h"];
    return CGSizeMake([w floatValue], [h floatValue]);
}

/**
 *  截取URL中的参数
 *
 *  @return NSMutableDictionary parameters
 */
- (NSMutableDictionary *)sl_parameterByComponentsSeparated {
    
    // 查找参数
    NSRange range = [self rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    // 以字典形式将参数返回
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSString *parametersString = [self substringFromIndex:range.location + 1];
    //
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];

            //转码操作，正常情况不影响
            NSString *key = [pairComponents.firstObject sl_stringByURLDecode];
            NSString *value = [pairComponents.lastObject sl_stringByURLDecode];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}


- (NSString *)sl_stringByURLDecode {
    if ([self respondsToSelector:@selector(stringByRemovingPercentEncoding)]) {
        return [self stringByRemovingPercentEncoding];
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        CFStringEncoding en = CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding);
        NSString *decoded = [self stringByReplacingOccurrencesOfString:@"+"
                                                            withString:@" "];
        decoded = (__bridge_transfer NSString *)
        CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
                                                                NULL,
                                                                (__bridge CFStringRef)decoded,
                                                                CFSTR(""),
                                                                en);
        return decoded;
#pragma clang diagnostic pop
    }
}


- (CGSize)sl_imageZoomSizeByComponentsSeparated {
    CGSize size = [self sl_imageSizeByComponentsSeparated];
    
    CGFloat widht = 0;
    CGFloat height = 0;

    widht = [[UIScreen mainScreen] bounds].size.width;

    if (size.height != 0) {
        height =  widht/size.width *size.height;
    }
    return CGSizeMake(widht, height);
}

+ (NSString *)sl_safeString:(NSString *)originString {
    return originString == nil ? @"" : originString;
}

-(void)lh_searchStringWithRegex:(NSString *)regexString complete:(void (^)(NSRange))complete{
    
    NSString *pattern = regexString; // 正则表达式，匹配任意一个子串
    
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    
    if (regex) {
        NSArray *matches = [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
        for (NSTextCheckingResult *match in matches) {
            NSRange range = match.range;
            if (complete) {
                complete(range);
            }
        }
    } else {
        NSLog(@"正则表达式错误: %@", error.localizedDescription);
    }
    
}

-(NSString *)markBankCard{
    
    if ([self sl_isValidNumber] ) {

        NSString *two = [self substringWithRange:NSMakeRange(self.length - 4, 4)];
        return [NSString stringWithFormat:@"****%@",two];
    }
    return self;
    
}
-(NSString *)markMobile{
    
    if ([self sl_isValidNumber] && self.length == 11) {
        NSString *one = [self substringWithRange:NSMakeRange(0, 3)];
        NSString *two = [self substringWithRange:NSMakeRange(7, 4)];
        return [NSString stringWithFormat:@"%@****%@",one,two];
    }
    return self;
    
}
-(NSString *)markName{
    
    if (self.length > 1 && ![self containsString:@"*"]) {
        NSString *one = [self substringWithRange:NSMakeRange(0, 1)];
        return [NSString stringWithFormat:@"%@*",one];
    }
    return self;
    
}
-(NSString *)markIdCard{
    
    if (self.length > 15 && ![self containsString:@"*"]) {
        NSString *one = [self substringWithRange:NSMakeRange(0, 4)];
        NSString *two = [self substringWithRange:NSMakeRange(self.length - 4, 4)];
        return [NSString stringWithFormat:@"%@****%@",one,two];
    }
    return self;
    
}

#pragma mark - Validation

- (BOOL)sl_isSuccessPhone {
    if (self.length == 11) {
        NSString *s = [self substringWithRange:NSMakeRange(0, 1)];
        if ([s isEqualToString:@"1"]) {
            return YES;
        }
    }
    return NO;
}
/** 全部是数字 */
- (BOOL)sl_isValidNumber {
    NSString *chineseRegex = @"^[0-9]*$";
    return [self sl_isValidByRegex:chineseRegex];
}

/** 全部是字母 */
- (BOOL)sl_isValidChar {
    NSString *chineseRegex = @"^[a-z]|[A-Z]*$";
    return [self sl_isValidByRegex:chineseRegex];
}

/**单独输入验证 数字和字母 */
- (BOOL)sl_isValidPassWord {
    NSString *chineseRegex = @"[a-z]|[A-Z]|[0-9]";
    return [self sl_isValidByRegex:chineseRegex];
}

/** 整串验证 */
- (BOOL)sl_isValidPassWordSuccess {
    NSString *chineseRegex = @"^(?!\\d+$)(?![a-zA-Z]+$)(?![^a-zA-Z0-9]+$)[[^a-zA-Z0-9]+\\w]{8,16}$";
    return [self sl_isValidByRegex:chineseRegex];
}

/** 验证是否是汉字 */
- (BOOL)sl_isAllChinese {
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}

/** 验证是否含有汉字 */
- (BOOL)sl_isHaveChinese {
    for(int i=0; i<[self length]; i++){
        int a = [self characterAtIndex:i];
        if( a>0x4e00 && a<0x9fff){
            return YES;
        }
    }
    return NO;
}

- (BOOL)sl_isValidByRegex:(NSString *)regex {
    NSString *tmp = [NSString stringWithFormat:@"%@",self];
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pre evaluateWithObject:tmp];
}

/** 获取字节长度 */
- (int)sl_stringConvertToInt
{
    int strlength = 0;
    char* p = (char*)[self cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[self lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++)
    {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
    }
    return strlength;
}

@end


@implementation NSString (SLTime)

+ (SLStringDate)sl_getDayDateInterval:(NSInteger)totle{
    NSInteger oneMinutes = 60;   //一分钟包含的秒数
    NSInteger oneHour = 60 * oneMinutes; //一小时包含的秒数
    NSInteger oneDay = 24 * oneHour;  // 一天包含的秒数
    
    NSInteger day = totle / oneDay; //剩余天数
    NSInteger hour = (totle % oneDay) / oneHour; //剩余的小时数
    NSInteger minutes = (totle % oneHour) / oneMinutes; //剩余的分钟数
    NSInteger seconds = totle % oneMinutes;
    SLStringDate date =  {day,hour,minutes,seconds};
    return date;
}

+ (SLStringDate)sl_getHourDateInterval:(NSInteger)totle{
    NSInteger oneMinutes = 60;   //一分钟包含的秒数
    NSInteger oneHour = 60 * oneMinutes; //一小时包含的秒数

    NSInteger hour = totle / oneHour; //剩余的小时数(可能超过24小时)
    NSInteger minutes = (totle % oneHour) / oneMinutes; //剩余的分钟数
    NSInteger seconds = totle % oneMinutes;
    SLStringDate date =  {0,hour,minutes,seconds};
    return date;
}

+ (SLStringDate)sl_getMinutesDateInterval:(NSInteger)totle{
    NSInteger oneMinutes = 60;   //一分钟包含的秒数
    NSInteger minutes = totle / oneMinutes; //剩余的分钟数
    NSInteger seconds = totle % oneMinutes;
    SLStringDate date =  {0,0,minutes,seconds};
    return date;
}


@end
